<!--执行任务 -->
<template>
  <a-drawer
    title="执行任务"
    :width="1100"
    :visible="drawerVisible"
    :maskClosable="drawMaskClosable"
    :body-style="{ paddingBottom: '80px' }"
    @close="closeD"
  >
    <div class="first">{{ taskName }}</div>
    <div class="basicAttr">
      <div class="attr">基本属性</div>
      <div v-if="messageList.length !== 0">
        <div
          class="messageContent"
          v-for="(item, index) in messageList"
          :key="index"
        >
          <div v-for="item1 in item.items" class="message_de" :key="item1.id">
            <detailMessage :attrList="item1"></detailMessage>
          </div>
        </div>
      </div>
      <a-empty v-else description="暂无数据" class="nodata" />
    </div>
    <div class="deliverable">
      <div class="attr">交付物</div>
      <div style="margin-bottom: 10px">
        <a-button type="primary" @click="startSgin">启动签审</a-button
        >&nbsp;&nbsp;
        <a-button @click="addDeliverRequire">新增交付物要求</a-button>
        <a-button style="margin-left: 10px" @click="editDeliverRequire"
          >编辑</a-button
        >
        <a-button style="margin-left: 10px" @click="deleteDeliverRequire"
          >移除</a-button
        >
      </div>
      <a-table
        :columns="deliverCols"
        :rowKey="'index'"
        :rowSelection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange,
        }"
        :data-source="tableData"
        :pagination="pagination"
        @change="handleTableChange"
      >
        <template slot="deliverableName" slot-scope="text, record">
          <a-input v-if="record['add'] || record['isEdit']" v-model="inputValue" @blur="onBlurChange" />
          <span v-else style="margin-right: 5px">{{ text }}</span>
        </template>
        <template slot="subjectName" slot-scope="text, record">
          <span
            v-if="!text && record['deliverable.name']"
            class="go-upload"
            @click="uploadBtn(record)"
            >上传</span
          >
          <a v-else @click="routerRequireDel(record)">{{ text }}</a>
          <!-- <span v-else>{{ text }}</span> -->
        </template>
      </a-table>
      <upload-delivery
        v-if="uploadVisible"
        :upload-modal-visible="uploadVisible"
        @closeUploadModal="closeUploadModal"
        @submitDeliver="submitDeliverHandler"
      ></upload-delivery>
    </div>
    <div class="footer">
      <a-button
        :style="{ marginRight: '8px' }"
        @click="commitApplyComplete('应用')"
      >
        应用
      </a-button>
      <a-button type="primary" @click="commitApplyComplete('确认')">
        确认
      </a-button>
    </div>
  </a-drawer>
</template>
<script>
import detailMessage from "@/components/singlePage/detailMessage";
import taskTable from "./comp/taskTable.vue";
import _ from "lodash";
import uploadDelivery from "@/components/uploadDelivery/index";
import { createDeliverInfo, updateDeliverInfo, deleteDeliverInfo } from "@api/planComponent";
import {
  getAttributeGroup,
  getDeliverableList,
  getLastResourceHour,
  updateDeliverabeSubject,
} from "@api/todoPage";
export default {
  name: "carryTask",
  components: {
    detailMessage,
    taskTable,
    uploadDelivery,
  },
  props: {
    drawerVisible_p: {
      type: Boolean,
      default: false,
    }, //是否展示抽屉
    oid: {
      type: String,
      default: "",
    }, //任务id
    taskName: {
      type: String,
      default: "产品定义评审",
    }, //任务名称
    assignmentOid: {
      type: String,
      default: "",
    },
    dataStatus: {
      type: String,
      default: "已完成",
    },
    action: {
      type: String,
      default: "执行任务",
    }, //当点击”操作“时显示详情；点击”任务名称“，显示详情+申请完成
    isHaveDelive: {
      type: String,
      default: "否",
    }, //是否有交付物
    drawMaskClosable: {
      type: Boolean,
      default: true,
    }, //点击蒙层是否允许关闭
    dataObj: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      loginName: "",
      textareaValue: "", //情况说明
      drawerVisible: this.drawerVisible_p,
      messageList: [], //基本属性（对象布局与属性）
      tableData: [],
      perc: 10, //完成百分比
      minPerc: 10, //完成百分比最小值
      // days: 0,//实际工期
      deliverableStatus: false, //交付物状态全部已完成
      loadingVisible: false,
      isRowsSelectVisible: true, //是否显示复选框
      rowSelection: true, //交付物是否显示多选
      deliverTableKey: "deliverable.oid", //交付物表格的key
      selectRowsDeliver: [], //选中的数据--交付物
      /**新增交付物要求 */
      deliverCols: [
        {
          title: "交付物要求",
          dataIndex: "deliverable.name",
          width: "22%",
          slotType: "showspan",
          scopedSlots: { customRender: "deliverableName" },
        },
        {
          title: "交付物",
          dataIndex: "subject.name",
          width: "40%",
          slotType: "upload",
          scopedSlots: { customRender: "subjectName" },
        },
        {
          title: "是否最新版本",
          dataIndex: "deliverable.lastVersion",
          width: "19%",
        },
        {
          title: "交付物状态",
          dataIndex: "deliverable.targetStatus",
          width: "19%",
        },
      ],
      uploadVisible: false, // 下载弹框显隐
      creators: [], //要移除数据的创建者
      inputValue: "", // input的值
      upRecord: {}, // 上传那一行的record
      selectedRowKeys: [],
      pagination: {
        page: 1, // 页码
        current: 1, // 当前页数
        total: 0, // 总数
        pageSize: 5, //每页中显示几条数据
        // pageSizeOptions: ["10", "20", "30"],
        showSizeChanger: false,
        showQuickJumper: true,
        showLessItems: true,
        showTotal: (total) => `共${total}条`, //分页中显示总的数据
      },
    };
  },
  computed: {
    slotColumns() {
      return this.deliverCols.filter((item) => item.slotType != undefined);
    },
  },
  watch: {
    drawerVisible_p(val) {
      this.drawerVisible = val;
    },
    oid(val) {
      this.oid = val;
    },
  },
  mounted() {
    this.loginName = JSON.parse(sessionStorage.getItem("userInfo")).loginName;
    this.getInfo();
    // this.getDeliverableHeader()
    this.getDeliverableData();
    this.getLastResourceHourB();
  },
  methods: {
    /**申请完成 */
    applyAchieveFun() {
      if (
        parseInt(this.dataObj["deliverable.count"]) == 1 &&
        this.dataObj["deliverable.status"] == "已发放C" &&
        this.dataObj["deliverable.plannableStatus"] != "待审核"
      ) {
        return true;
      } else {
        return false;
      }
    },
    closeD() {
      this.$emit("closeDraw");
    },
    commitApplyComplete(type) {
      if (type == "应用") {
        let editData = this.tableData.filter((v) => v["isEdit"] == true)
        if (editData[0] && editData[0]['isEdit']) {
          this.editDelivers(editData)
        } else {
          this.addDlivers(type); //点应用按钮  新增
        }
      } else if (type == "确认") {
        let editData = this.tableData.filter((v) => v["isEdit"] == true)
        if (editData[0] && editData[0]['isEdit']) {
          this.editDelivers(editData)
        } else {
          this.addDlivers(type); //点应用按钮  新增
        }
        this.$emit("closeDraw"); //关闭弹框
        this.$store.commit("commitApplyAdd"); //提交vueX，刷新页面数据
        // this.commitApplyComplete2()         //点确认按钮  申请完成任务
      }
    },
    //完成审核，关闭抽屉
    // commitApplyComplete() {
    //   /*新增交付物要求，在输入框获取焦点，但是未输入内容的时候，点击确认，会提示输入*/
    //   // if (!this.requireStstus) {
    //   //   return
    //   // }
    //   if ((this.deliverableStatus || this.isHaveDelive === '否') && this.dataStatus !== '已完成' && this.dataStatus !== '待审核' && this.action === '执行任务') {
    //     if (this.perc == '' || this.days == '' || this.textareaValue == '') {
    //       this.$message.error('请输入必需项！')
    //       // this.$emit("closeDraw");
    //     } else {
    //       let parm = {
    //         resources: [
    //           {
    //             assignmentOid: this.assignmentOid,
    //             completePercent: parseInt(this.perc),
    //             completeTime: parseInt(this.days),
    //             comment: this.textareaValue
    //           }
    //         ]
    //       }
    //       sumResource(parm).then(res => {
    //         if (res && res.status === 200) {
    //           if (res.data.success == true) {
    //             this.$message.success('申请成功！')
    //             this.perc = null
    //             this.minPerc = null
    //             this.days = null
    //             this.textareaValue = ''
    //             this.$store.commit('commitApplyAdd')//刷新抽屉中的数据
    //             this.$emit("closeDraw");
    //           } else {
    //             this.$message.error(res.data.message)
    //           }
    //         } else {
    //           this.$message.error('接口连接失败！')
    //         }
    //       })
    //     }
    //   } else {
    //     this.$emit("closeDraw");
    //   }
    // },
    //获取任务基本信息
    getInfo() {
      let parms = {
        oid: this.oid,
      };
      getAttributeGroup(parms).then((res) => {
        // console.log(res.data[0].rows)
        if (res && res.status === 200) {
          if (res.data && res.data.success) {
            if (
              res.data.data[0] &&
              res.data.data[0].rows &&
              res.data.data[0].rows.length > 0
            ) {
              this.messageList = res.data.data[0].rows;
            } else {
              this.messageList = [];
            }
          } else {
            this.messageList = [];
            this.$message.error(res.data.message);
          }
        } else {
          this.$message.error("接口失败");
        }
      });
    },
    /*//获取交付物表头
    getDeliverableHeader() {
      getDeliverableAttrs().then(res => {
        this.tableColumns = []
        if (res && res.status === 200) {
          if (res.data.data && res.data.data.length > 0) {
            let item = {}
            for (let i = 0; i < res.data.data.length; i++) {
              item = {}
              item.title = res.data.data[i].displayName
              item.dataIndex = res.data.data[i].name
              // item.title = res.data[i].displayName
              this.tableColumns.push(item)
            }
          }
        } else {
          this.$message.error('获取基本属性失败')
        }
      })
    },*/
    //获取交付物表格数据
    getDeliverableData(type) {
      this.loadingVisible = true;
      let parms = {
        oid: this.oid,
      };
      getDeliverableList(parms).then((res) => {
        this.tableData = [];
        if (res && res.status === 200) {
          if (res.data && res.data.success) {
            if (res.data.data && res.data.data.length > 0) {
              this.$set(this,"selectedRowKeys",[])
              this.$set(this,"selectRowsDeliver",[])
              this.tableData = res.data.data;
              this.tableData.forEach((v,idx) => {
                this.$set(v, 'index', idx)
                this.$set(v, 'isEdit', false)
              })
              if (type === "确认") {
                this.$emit("closeDraw");
              }
              // 交付物状态：['已发放A','已发放B','已发放C']
              let status = _.filter(res.data.data, (rec) => {
                return rec["deliverable.targetStatus"].indexOf("已发放") < 0;
              });
              // console.log('status-----------------',status)
              if (status.length > 0) {
                this.deliverableStatus = false;
              } else {
                this.deliverableStatus = true;
              }
              this.loadingVisible = false;
            } else {
              this.tableData = [];
              this.loadingVisible = false;
            }
          } else {
            this.loadingVisible = false;
            this.$message.error(res.data.message);
          }
        } else {
          this.loadingVisible = false;
          this.$message.error("接口失败");
        }
      });
    },
    //获取上一次汇报工时的记录
    getLastResourceHourB() {
      let parm = {
        resources: [
          {
            assignmentOid: this.assignmentOid,
          },
        ],
      };
      getLastResourceHour(parm).then((res) => {
        if (res && res.status === 200) {
          if (res.data && res.data.success && res.data.data.length > 0) {
            this.perc = res.data.data[0].completePercent;
            this.minPerc = res.data.data[0].completePercent;
            this.textareaValue = "";
          } else {
            this.perc = null;
            this.minPerc = null;
            this.textareaValue = "";
          }
        } else {
          this.$message.error("获取上一次的完成百分比失败");
        }
      });
    },
    //点击交付物--跳转至交付物详情页面
    routerRequireDel(val) {
      console.log(val);
      if (val["subject.oid"].indexOf('ProjectTaskBook') != -1) {
        this.$router.push({path: "/single/projectPaper/mainTaskBook", query: { bookOid: val["subject.oid"] } })
      } else {
        //交付物页面（详情界面）
        let fileSingleTableItem_s = [{
          oid: val["subject.oid"], //流程oid
          workItemName: "", //流程节点名称
          state: "", //流程状态
          workItemState: val["deliverable.targetStatus"], //交付物状况
        }];
        sessionStorage.setItem(
          "fileSingleTableItem",
          JSON.stringify(fileSingleTableItem_s)
        );
        this.$store.commit("SET_PROJECT_FILE_TITLE", "");
        this.$router.push({
          path: "/single/fileSingle/examineProject",
        });
      }
    },
    //启动签审
    startSgin() {
      console.log("启动签审----------------", this.selectRowsDeliver);
      if (this.selectRowsDeliver.length < 1) {
        this.$message.error("请选择交付物！");
        return;
      } else {
        let stateData = _.filter(this.selectRowsDeliver, (o) => {
          return o["deliverable.targetStatus"].indexOf("正在工作") < 0;
        });
        let checkOutData = _.filter(this.selectRowsDeliver, (o) => {
          return o["subject.isCheckOut"] == "true";
        });
        if (stateData.length > 0 || checkOutData.length > 0) {
          this.$message.error("请选择正在工作并且未检出的文档！");
          return;
        }
        // 过滤含有任务书文件
        let hasProcess = this.selectRowsDeliver.some(v => v['subject.oid'] && v['subject.oid'].indexOf('ProjectTaskBook') != -1)
        if (hasProcess) {
          this.$message.error("您选中的内容包含任务书，请创建立项评审发布项目任务书！");
          return
        }
        // 过滤非任务书及文档内容
        let otherType = this.selectRowsDeliver.some(k => k['subject.oid'] && k['subject.oid'].indexOf('ProjectTaskBook') == -1 && k['subject.oid'].indexOf('WTDocument') == -1)
        if (otherType) {
          this.$message.error("非文档类型不能起流程！");
          return
        }
        let newSelectDeliverData = [];
        this.selectRowsDeliver.map((item) => {
          let newSelectDeliverDataOnce = {};
          console.log(item);
          newSelectDeliverDataOnce.oid = item["subject.oid"];
          newSelectDeliverDataOnce.type = item["subject.type"];
          newSelectDeliverData.push(newSelectDeliverDataOnce);
        });
        let sessArr = {
          tableArr: newSelectDeliverData,
        };
        console.log(sessArr);
        sessionStorage.setItem(
          "fileSingleDataByStart",
          JSON.stringify(sessArr)
        );
        this.$router.push("single/fileSingle/fileStart");
      }
    },
    //上传交付物点击“确定”执行的操作
    uploadFile(val, thisRecord) {
      let parm = {
        deliverableOid: thisRecord["deliverable.oid"], //当前交付物的deliverable.oid
        subjectOid: val.oid,
      };
      updateDeliverabeSubject(parm).then((res) => {
        if (res && res.status === 200) {
          if (res.data && res.data.success) {
            this.$message.success("上传成功！");
            this.getDeliverableData();
            this.$nextTick(() => {
              this.$refs.carryTaskDeTable && this.$refs.carryTaskDeTable.closeUploadModal();
            })
          } else {
            this.$message.success("上传失败！");
          }
        } else {
          this.$message.error("接口失败");
        }
      });
    },
    /**新增交付物要求 */
    addDeliverRequire() {
      this.inputValue = "";
      if (
        this.tableData.some(
          (item) =>
            item["deliverable.oid"] == undefined ||
            item["deliverable.oid"] == ""
        )
      ) {
        this.$message.error("每次只能新增一个交付物");
        return;
      }
      this.tableData.forEach(item => {
        item.isEdit = false
      })
      // this.requireStstus = false
      this.tableData.push({
        "deliverable.name": "",
        "subject.name": "",
        "deliverable.lastVersion": "",
        "deliverable.targetStatus": "",
        "add": "add",
        "index": this.tableData.length
      });
      let lengthNum = this.tableData.length;
      let num = Math.ceil(lengthNum / 5);
      this.pagination.current = num;
    },
    handleTableChange(pagination, filters) {
      this.pagination.current = pagination.current;
    },
    /*调用接口 */
    addDlivers(type) {
      let arr = this.tableData.filter((v) => {
        return v["deliverable.name"] === "";
      });
      if (arr.length > 0 && !this.inputValue) {
        this.$message.error("请输入交付物要求名称");
        return;
      }
      let status = this.tableData.some((v) => v["add"] == "add");
      if (status) {
        let data = {
          oid: this.oid,
          name: this.inputValue,
          subjectOid: "",
        };
        createDeliverInfo(data).then((res) => {
          if (res && res.data.success) {
            this.$message.success("添加成功");
            this.getDeliverableData(type);
          } else {
            this.$message.error("添加失败");
          }
        });
      } else {
        this.$emit("closeDraw");
      }
    },
    //完成审核，关闭抽屉
    commitApplyComplete2() {
      // let parm = {
      //   resources: [
      //     {
      //       assignmentOid: this.assignmentOid,
      //       completePercent: parseInt(this.perc),
      //       comment: this.textareaValue||"工作已完成，申请关闭"
      //     }
      //   ]
      // }
      // console.log(parm,this.perc);
      // sumResource(parm).then(res => {
      //   if (res && res.status === 200) {
      //     if (res.data.success == true) {
      //       this.$message.success('申请成功！')
      //       this.perc = null
      //       this.minPerc = null
      //       // this.days = null
      //       this.textareaValue = ''
      //       this.$store.commit('commitApplyAdd')//刷新抽屉中的数据
      //       this.$emit("closeDraw");
      //       this.$store.commit('clearSelectedTableData')//关闭抽屉后清空选中的数组
      //     } else {
      //       this.$message.error(res.data.message)
      //     }
      //   } else {
      //     this.$message.error('接口连接失败！')
      //   }
      // })
    },
    /**输入框失去焦点 */
    onBlurChange() {
      // this.confirmModel = true
    },
    // confirm() {
    //   this.addDlivers()
    //   this.confirmModel = false
    // this.requireStstus = false
    // },
    // cancel() {
    //   this.confirmModel = false
    // },
    uploadBtn(record) {
      this.upRecord = record;
      this.uploadVisible = true;
    },
    //关闭上传交付物弹窗
    closeUploadModal() {
      this.uploadVisible = false;
    },
    submitDeliverHandler(val) {
      this.uploadVisible = false;
      this.uploadFile(val, this.upRecord);
    },
    /**表格多选 */
    // 多选
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectRowsDeliver = selectedRows;
    },
    /**编辑 */
    editDeliverRequire() {
      if (this.selectRowsDeliver.length == 0) {
        this.$message.warn('请选择需要编辑的内容')
        return false
      }
      if (this.selectRowsDeliver.length > 1) {
        this.$message.warn('每次最多编辑一个')
        return false
      }
      this.inputValue = this.selectRowsDeliver[0]['deliverable.name']
      this.tableData.forEach((k,idx) => {
        if (this.selectRowsDeliver[0]['deliverable.oid'] === k['deliverable.oid']) {
          this.$set(k, 'isEdit', true)
        } else {
          this.$set(k, 'isEdit', false)
        }
      })
    },
    editDelivers(v) {
      let data = {
        oid: v[0]['deliverable.oid'],
        name: this.inputValue,
        subjectOid: "",
      };
      updateDeliverInfo(data).then((res) => {
        if (res && res.data.success) {
          this.$message.success('编辑成功')
          this.tableData.forEach(k => {
            if (this.selectRowsDeliver[0]['deliverable.oid'] === v[0]['deliverable.oid']) {
              this.$set(k, 'isEdit', false)
            }
          })
          this.getDeliverableData()
        } else {
          this.$message.success('编辑失败')
        }
        
      });
    },
    /**移除 */
    deleteDeliverRequire() {
      this.creators = [];
      if (this.selectRowsDeliver.length > 0) {
        let ids = [];
        const delIds = this.selectedRowKeys.sort((pre, next) => next - pre);
        this.tableData.forEach((item, index) => {
          if (this.selectedRowKeys.includes(index) && item["deliverable.oid"]) {
            ids.push(item["deliverable.oid"]);
            this.creators.push(item["canDelete"]); //把交付物的创建者放在一起
          }
        });
        if (this.creators.every((item) => item === "true")) {
          console.log("选择的数据没有包含其他人", this.creators);
          deleteDeliverInfo({
            oid: this.oid,
            oids: JSON.stringify(ids),
          }).then((res) => {
            if (res.data.success == "true") {
              //删除移除的数据
              this.selectedRowKeys = [];
              delIds.forEach((item) => {
                this.tableData.splice(item, 1);
              });
              this.$message.success("移除成功!");
              this.getDeliverableData();
            } else {
              this.$message.error(res.data.message);
            }
          });
        } else {
          this.$message.warn("您无权移除项目经理委派的交付要求，如需调整，请与项目经理联系！");
        }
      } else {
        this.$message.warn("请选择要移除的内容");
      }
    },
  },
};
</script>
<style lang="less" scoped>
/deep/ .ant-drawer-body {
  padding: 10px 20px;
}
.attr {
  font-size: 16px;
  color: rgba(0, 0, 0, 0.85);
  font-weight: 500;
  margin-bottom: 16px;
}
.first {
  color: rgba(0, 0, 0, 0.85);
  font-size: 20px;
  font-weight: 500;
}
.basicAttr {
  margin-top: 16px;
  .message {
    padding: 5px 20px 5px 0;
  }
}
.deliverable {
  margin-top: 20px;
}
.applyAchieve {
  width: 700px;
  margin-top: 20px;
  /deep/ .ant-row {
    margin-bottom: 10px;
  }
  .label {
    margin-top: 0px;
  }
  .appInput {
    width: 100%;
    margin-top: 10px;
  }
}
.footer {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 100%;
  border-top: 1px solid #e9e9e9;
  padding: 10px 16px;
  background: #fff;
  text-align: right;
  z-index: 1;
}
.messageContent {
  margin-bottom: 10px;
  display: flex;
  .message_de {
    width: 25%;
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
    .messageList {
      min-width: 25%;
      margin: 5px 0;
      font-size: 14px;
      text-align: right;
      display: flex;
      justify-content: flex-start;
    }
  }
}
.nodata {
  padding: 10px 0 20px 0;
}
.go-upload {
  display: inline-block;
  border: 1px solid #386bd7;
  background: #386bd7;
  color: #fff;
  padding: 0 10px;
  cursor: pointer;
  font-size: 12px;
}
</style>